package com.yb0os1.beans;

import com.yb0os1.exception.BeanException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleBeanFactory implements BeanFactory {
    private final List<String> beanNames = new ArrayList<>();
    private final List<BeanDefinition> beanDefinitions = new ArrayList<>();
    private final Map<String, Object> beanInstances = new HashMap<>();

    @Override
    public String toString() {
        return "SimpleBeanFactory{" +
                "beanNames=" + beanNames +
                ", beanDefinitions=" + beanDefinitions +
                ", beanInstances=" + beanInstances +
                '}';
    }

    @Override
    public Object getBean(String name) throws BeanException {
        Object o = beanInstances.get(name);
        if (o == null){
            int i = beanNames.indexOf(name);
            if(i==-1){
                throw new BeanException("bean not found");
            }
            BeanDefinition beanDefinition = beanDefinitions.get(i);
            if (beanDefinition == null){
                throw new BeanException("beanDefinition not found");
            }
            try {
                o = Class.forName(beanDefinition.getClassName()).newInstance();
                beanInstances.put(name,o);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return o;
    }

    @Override
    public void registerBeanDefinition(String name, BeanDefinition beanDefinition) {
        beanNames.add(name);
        beanDefinitions.add(beanDefinition);
    }
}
